package com.sky.config;

import com.sky.interceptor.GlobalInterceptor;
import com.sky.json.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.List;

/**
 *  springMvc 配置类，注册web层相关组件
 */
@Slf4j
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {


    /**
     * 添加静态资源映射   html、css、js等前端代码的映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("springmvc 静态资源映射配置......");

        //Swagger相关静态文件映射  过滤器、拦截器中需要放行
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

    }




    //拦截器bean
    /*@Resource
    private GlobalInterceptor globalInterceptor;*/

    @Resource
    private RedisTemplate redisTemplate;

    //拦截器配置
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("springmvc 全局拦截器配置......");
        //registry.addInterceptor(globalInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(new GlobalInterceptor(redisTemplate)).addPathPatterns("/**");
    }




    /**
     * 拓展 Spring MVC框架的消息转换器
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("springmvc 消息转换器拓展......");
        // 1.创建一个消息转换器
        MappingJackson2HttpMessageConverter httpMessageConverter = new MappingJackson2HttpMessageConverter();
        // 2.为消息转换器设置一个对象转换器，用来做java对象序列化json，以及json反序列化为java对象
        httpMessageConverter.setObjectMapper(new JacksonObjectMapper());
        // 3.添加到框架底层容器，且为消息转换器集合第一个元素
        converters.add(0, httpMessageConverter);
    }

}
